package com.miaowang.salad.activity;

import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.miaowang.salad.Common;
import com.miaowang.salad.data.OkHttpResponseData;
import com.miaowang.salad.data.ServiceDetailData;
import com.miaowang.salad.jobqueue.CancelServiceRequestJob;
import com.miaowang.salad.jobqueue.GetServiceDetailJob;
import com.miaowang.salad.jobqueue.JobEvents;
import com.miaowang.salad.util.CheckUtil;
import com.miaowang.salad.util.PrefUtils;
import com.path.android.jobqueue.Job;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * @author weihe 我的服务详情
 */
public class ServiceDetailActivity extends BaseActivity {

	TextView tvRescueState;
	TextView tvCustomerName;
	TextView tv_rescue_phone;
	TextView tv_rescue_chepai;
	TextView tv_rescue_chexing;
	TextView tv_rescue_car_color;
	TextView tv_rescue_type;
	Button btnMap;
	Button btnDetailRefresh;
	Button btnCancel;
	private String id;
	private ProgressDialog pd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rescue_detail_info);

		id = getIntent().getStringExtra("id");

		tvRescueState = (TextView) findViewById(R.id.tv_rescue_state);
		tvCustomerName = (TextView) findViewById(R.id.tv_rescue_user_info);
		tv_rescue_phone = (TextView) findViewById(R.id.tv_rescue_phone);
		tv_rescue_chepai = (TextView) findViewById(R.id.tv_rescue_chepai);
		tv_rescue_chexing = (TextView) findViewById(R.id.tv_rescue_chexing);
		tv_rescue_car_color = (TextView) findViewById(R.id.tv_rescue_car_color);
		tv_rescue_type = (TextView) findViewById(R.id.tv_rescue_type);
		btnMap = (Button) findViewById(R.id.btn_map);
		btnDetailRefresh = (Button) findViewById(R.id.btn_detail_refresh);
		btnCancel = (Button) findViewById(R.id.btn_cancel);
		initControl();
		getServiceDetailFromServer();
	}

	private void initData(ServiceDetailData data) {
		tvRescueState.setText(data.getStatus());
		tvCustomerName.setText(data.getName());
		tv_rescue_phone.setText(data.getPhone());
		tv_rescue_chepai.setText(data.getCar_license_no());
		tv_rescue_chexing.setText(data.getCar_model());
		tv_rescue_car_color.setText(data.getCar_color());
		tv_rescue_type.setText(data.getService_type());
		if("已取消".equals(data.getStatus()) == false  && "已完成".equals(data.getStatus())==false){
			btnCancel.setVisibility(View.VISIBLE);
		}else{
			btnCancel.setVisibility(View.GONE);
		}
	}

	private void initControl() {
		btnMap.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.putExtra("id", id);
				intent.setClass(ServiceDetailActivity.this,
						RescueCarMapActivity.class);
				startActivity(intent);
			}
		});

		btnDetailRefresh.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				getServiceDetailFromServer();
			}
		});
		btnCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				cancelCurrentService();
			}
		});

	}

	private void getServiceDetailFromServer() {
		if (pd == null) {
			pd = new ProgressDialog(ServiceDetailActivity.this);
		}
		pd.setTitle("正在获取任务详细信息...");
		pd.show();
		Job job = new GetServiceDetailJob(id, 1);
		CarmapApplication.getInstance().getJobManager().addJobInBackground(job);
	}

	private void cancelCurrentService() {
		if (pd == null) {
			pd = new ProgressDialog(ServiceDetailActivity.this);
		}
		pd.setTitle("正在取消当前任务...");
		pd.show();
		Job job = new CancelServiceRequestJob("");
		CarmapApplication.getInstance().getJobManager().addJobInBackground(job);
	}

	// EventsBus
	@Subscribe(threadMode = ThreadMode.MainThread)
	public void onEventMainThread(JobEvents.JobSuccess e) {
		if (e.getJobCode() == JobEvents.GET_SERVICE_REQUESTS_ID) {
			OkHttpResponseData msg = (OkHttpResponseData) e.getResult();
			if (pd != null) {
				pd.dismiss();
			}

			if (msg != null) {
				Toast.makeText(ServiceDetailActivity.this, msg.getMsg(),
						Toast.LENGTH_SHORT).show();
				if (!CheckUtil.isEmpty(msg.getData())) {
					try {
						JSONObject json = new JSONObject(msg.getData());
						if (json.has("service_request")) {
							String jobString = json
									.getString("service_request");
							if (!CheckUtil.isEmpty(jobString)) {
								ServiceDetailData data = JSON.parseObject(
										jobString, ServiceDetailData.class);
								initData(data);
							} else {
								Toast.makeText(ServiceDetailActivity.this,
										"获取任务详情失败", Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(ServiceDetailActivity.this,
									"获取任务详情失败", Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e1) {
						e1.printStackTrace();
					}

				} else {
					Toast.makeText(ServiceDetailActivity.this, msg.getMsg(),
							Toast.LENGTH_SHORT).show();
				}

			} else {
				Toast.makeText(ServiceDetailActivity.this, msg.getMsg(),
						Toast.LENGTH_SHORT).show();
			}
		} else if (e.getJobCode() == JobEvents.CANCEL_SERVICE_REQUESTS) {
			if (pd != null) {
				pd.dismiss();
			}
			OkHttpResponseData msg = (OkHttpResponseData) e.getResult();
			dealCancelRequest(msg);
		}
	}

	@Subscribe(threadMode = ThreadMode.MainThread)
	public void onEventMainThread(JobEvents.JobFailure e) {
		if (e.getJobCode() == JobEvents.GET_SERVICE_REQUESTS_ID) {
			if (pd != null) {
				pd.dismiss();
			}
		} else if (e.getJobCode() == JobEvents.CANCEL_SERVICE_REQUESTS) {
			if (pd != null) {
				pd.dismiss();
			}
		}
	}

	private void dealCancelRequest(OkHttpResponseData msg) {

		int code = msg.getCode();
		if (code == 0) {
			try {
				String data = msg.getData();
				if (CheckUtil.isEmpty(data)) {
					Toast.makeText(ServiceDetailActivity.this, "任务取消失败，请检查网络",
							Toast.LENGTH_SHORT).show();
					return;
				}
				JSONObject json = new JSONObject(msg.getData());
				if (json.has("service_request")) {
					String service_request = json.getString("service_request");
					if (!CheckUtil.isEmpty(service_request)) {
						JSONObject idJson = new JSONObject(service_request);
						if (idJson != null) {
							// 返回值中应该有任务的详细信息
							if (idJson.has("id")) {
								PrefUtils.putString(ServiceDetailActivity.this,
										Common.PREF_CURRENT_TASK_ID, "");
								// EventBus.getDefault()
								// .post(new JobEvents.JobSuccess<>(
								// JobEvents.SEND_SERVICE_REQUESTS_SUCCESS));
								tvRescueState.setText("已取消");
								ServiceDetailActivity.this.finish();
							} else {
								Toast.makeText(ServiceDetailActivity.this,
										"任务取消失败，请检查网络", Toast.LENGTH_SHORT)
										.show();
							}
						}
					} else {
						Toast.makeText(ServiceDetailActivity.this,
								"任务取消失败，请检查网络", Toast.LENGTH_SHORT).show();
					}

				} else {
					Toast.makeText(ServiceDetailActivity.this, "任务取消失败，请检查网络",
							Toast.LENGTH_SHORT).show();
				}

			} catch (JSONException e) {
				Toast.makeText(ServiceDetailActivity.this, "任务取消失败，请检查网络",
						Toast.LENGTH_SHORT).show();
				e.printStackTrace();
				return;
			}
			// 保存当前任务信息
		} else {
			Toast.makeText(ServiceDetailActivity.this, msg.getMsg(),
					Toast.LENGTH_SHORT).show();
		}

	}
}
